package com.woniu.exception;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.util.function.Supplier;

/**
 * gageway网关过滤器全局异常类
 */

@Component
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {

    ObjectMapper obj = new ObjectMapper();
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()){
            return Mono.error(ex);
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        return response.writeWith(Mono.fromSupplier(new Supplier<DataBuffer>() {
            @Override
            public DataBuffer get() {
                DataBufferFactory dataBufferFactory = response.bufferFactory();
                try {
                    return dataBufferFactory.wrap(obj.writeValueAsBytes(ex.getMessage()));
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                    return dataBufferFactory.wrap(new byte[0]);
                }
            }
        }));
    }
}
